package io.mft.commons.db;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hutool.json.JSONUtil;
import io.mft.commons.config.ConfigProvider;
import io.mft.commons.db.mapper.TbWhere;
import io.mft.commons.db.mapper.Where;
import io.mft.commons.db.mapper.Where.WhereType;
import io.mft.commons.db.mapper.exception.MapperException;
import io.mft.commons.function.response.kv.KVMap;
public class SQLTextTbParameter implements ISQLParameter{
	private static final Logger log = LoggerFactory.getLogger(SQLTextTbParameter.class);
	private String tbName;
	private String sqlId;
	private String datasourceId;
	private Class<?> mapperClass;
	public void setTbName(String tbName) {
		this.tbName = tbName;
	}
	public String getTbName() {
		return tbName;
	}
	@Override
	public String sqlId() {
		return sqlId;
	}
	@Override
	public void sqlId(String sqlId) {
		this.sqlId=sqlId;
	}
	@Override
	public SQL sqlText(KVMap parameter) {
		Set<?> keys=parameter.keySet();
		int k=0;
		List<Where> wheres=new ArrayList<>();
		for (Object key : keys) {
			Object object = parameter.get(key);
			if (object instanceof TbWhere) {
				if (k>0) {
					throw new MapperException("浠呬笖鏀寔涓�涓猅bWhere鍙傛暟妯″紡锛岃妫�鏌ワ紒");
				}
				TbWhere tbWhere=(TbWhere)object;
				tbName=tbWhere.getTbName();
				wheres.addAll(tbWhere.getWheres());
				k++;
			}else {
				Where where=new Where();
				where.setField(String.valueOf(key));
				where.setType(WhereType.eq);
				where.setValue(parameter.get(key));
				wheres.add(where);
			}
		}
		StringBuffer buffer=new StringBuffer("select t.* from "+tbName+" t where 1=1");
		Object[] args=new Object[wheres.size()];
		 String[] argKeys=new String[args.length];
		int i=0;
		for (Where where : wheres) {
			buffer.append(" and ");
			buffer.append("t."+where.expression());
			args[i]=where.getValue();
			argKeys[i]=where.getField();
			i++;
		}
		SQL sql=new SQL(buffer.toString(),argKeys, args);
		String isPrintSQLText=ConfigProvider.get("db.isPrintSQLText", "0");
		if ("1".equals(isPrintSQLText)) {
			log.info("\nsqlId:\n"+mapperClass.getName()+"--->>>>>>"+sqlId+"\nsqlText:\n"+sql.getSql()+"\n参数:\n"+JSONUtil.toJsonStr(sql.getArgs()));
		}
		return sql;
	}
	@Override
	public void mapper(Class<?> mapperClass) {
		this.mapperClass = mapperClass;
	}

	@Override
	public Class<?> mapper() {
		return mapperClass;
	}
	@Override
	public void datasourceId(String datasourceId) {
		this.datasourceId=datasourceId;
	}

	@Override
	public String datasourceId() {
		return datasourceId;
	}
}
